<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="食谱类型" prop="menuType">
        <el-select v-model="queryParams.menuType" placeholder="请选择食谱类型" clearable @change="handleQuery">
          <el-option label="糖尿病食谱" :value="1" />
          <el-option label="高血压食谱" :value="2" />
          <el-option label="素食食谱" :value="3" />
          <el-option label="低盐食谱" :value="4" />
          <el-option label="低脂食谱" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['catering:careMenu:add']">
          新增关怀食谱
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['catering:careMenu:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['catering:careMenu:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['catering:careMenu:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="careMenuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="食谱类型" align="center" prop="menuType" width="120">
        <template #default="scope">
          <el-tag :type="getMenuTypeTagType(scope.row.menuType)">
            {{ getMenuTypeName(scope.row.menuType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="菜品名称" align="center" prop="dishName" width="150" />
      <el-table-column label="菜品图片" align="center" prop="dishImage" width="120">
        <template #default="scope">
          <image-preview :src="scope.row.dishImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="食材" align="center" prop="ingredients" :show-overflow-tooltip="true" />
      <el-table-column label="营养信息" align="center" prop="nutritionInfo" :show-overflow-tooltip="true" />
      <el-table-column label="适用人群" align="center" prop="suitableCrowd" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="dark">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['catering:careMenu:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['catering:careMenu:remove']">
            删除
          </el-button>
          <el-button link type="primary" :icon="scope.row.status === 0 ? 'Unlock' : 'Lock'" @click="handleStatusChange(scope.row)">
            {{ scope.row.status === 0 ? '启用' : '禁用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改关怀食谱对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="careMenuRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="食谱类型" prop="menuType">
          <el-select v-model="form.menuType" placeholder="请选择食谱类型" style="width: 100%">
            <el-option label="糖尿病食谱" :value="1" />
            <el-option label="高血压食谱" :value="2" />
            <el-option label="素食食谱" :value="3" />
            <el-option label="低盐食谱" :value="4" />
            <el-option label="低脂食谱" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品名称" prop="dishName">
          <el-input v-model="form.dishName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品图片" prop="dishImage">
          <image-upload v-model="form.dishImage" />
        </el-form-item>
        <el-form-item label="食材" prop="ingredients">
          <el-input v-model="form.ingredients" type="textarea" :rows="3" placeholder="请输入食材信息" />
        </el-form-item>
        <el-form-item label="营养信息" prop="nutritionInfo">
          <el-input v-model="form.nutritionInfo" type="textarea" :rows="3" placeholder="请输入营养信息" />
        </el-form-item>
        <el-form-item label="制作方法" prop="preparationMethod">
          <el-input v-model="form.preparationMethod" type="textarea" :rows="4" placeholder="请输入制作方法" />
        </el-form-item>
        <el-form-item label="适用人群" prop="suitableCrowd">
          <el-input v-model="form.suitableCrowd" type="textarea" :rows="2" placeholder="请输入适用人群" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注信息（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CareMenu">
import { listCareMenu, getCareMenu, delCareMenu, addCareMenu, updateCareMenu, exportCareMenu } from '@/api/catering/careMenu'

const { proxy } = getCurrentInstance()

const careMenuList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const baseUrl = import.meta.env.VITE_APP_BASE_API;
function getFullImageUrl(url) {
  if (!url) return '';
  // 如果已经是完整的URL（阿里云OSS），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  // 如果是相对路径，拼接baseUrl
  return baseUrl + url;
}

const data = reactive({
  form: {
    status: 1
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    menuType: null,
    status: null
  },
  rules: {
    menuType: [
      { required: true, message: '食谱类型不能为空', trigger: 'change' }
    ],
    dishName: [
      { required: true, message: '菜品名称不能为空', trigger: 'blur' }
    ],
    ingredients: [
      { required: true, message: '食材不能为空', trigger: 'blur' }
    ],
    nutritionInfo: [
      { required: true, message: '营养信息不能为空', trigger: 'blur' }
    ],
    preparationMethod: [
      { required: true, message: '制作方法不能为空', trigger: 'blur' }
    ],
    suitableCrowd: [
      { required: true, message: '适用人群不能为空', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询关怀食谱列表 */
function getList() {
  loading.value = true
  listCareMenu(queryParams.value).then(response => {
    careMenuList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 获取食谱类型名称
function getMenuTypeName(menuType) {
  const menuTypeMap = {
    1: '糖尿病食谱',
    2: '高血压食谱',
    3: '素食食谱',
    4: '低盐食谱',
    5: '低脂食谱'
  }
  return menuTypeMap[menuType] || menuType
}

// 获取食谱类型标签样式
function getMenuTypeTagType(menuType) {
  const tagTypeMap = {
    1: 'danger',
    2: 'warning',
    3: 'info',
    4: 'success',
    5: 'primary'
  }
  return tagTypeMap[menuType] || ''
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    menuType: null,
    dishName: null,
    dishImage: null,
    ingredients: null,
    nutritionInfo: null,
    preparationMethod: null,
    suitableCrowd: null,
    status: 1,
    remark: null
  }
  proxy.resetForm('careMenuRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加关怀食谱'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getCareMenu(id).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改关怀食谱'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['careMenuRef'].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCareMenu(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addCareMenu(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除关怀食谱编号为"' + ids + '"的数据项？').then(function() {
    return delCareMenu(ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

/** 状态变更操作 */
function handleStatusChange(row) {
  const statusText = row.status === 1 ? '禁用' : '启用'
  proxy.$modal.confirm('确认要' + statusText + '该关怀食谱吗？').then(function() {
    const newStatus = row.status === 1 ? 0 : 1
    return updateCareMenu({ ...row, status: newStatus })
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess(statusText + '成功')
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('catering/careMenu/export', {
    ...queryParams.value
  }, `careMenu_${new Date().getTime()}.xlsx`)
}

getList()
</script> 